<template>
  <div class="wrapper">
    <!-- 头部 -->
    <header>
      <i class="fa fa-arrow-left" @click="goBack"></i>
      <div class="title">订单支付</div>
      <div class="placeholder"></div>
    </header>

    <!-- 订单信息 -->
    <div class="order-info">
      <h3>订单信息</h3>
      <div class="order-summary">
        <div class="info-item">
          <span>订单编号:</span>
          <span>{{ orderInfo?.orderId }}</span>
        </div>
        <div class="info-item">
          <span>商家名称:</span>
          <span>{{ orderInfo?.businessName || orderInfo?.shopName }}</span>
        </div>
        <div class="info-item">
          <span>订单金额:</span>
          <span class="price">¥{{ orderInfo?.orderTotal || orderInfo?.totalPrice }}</span>
        </div>
      </div>
    </div>

    <!-- 配送地址 -->
    <div class="delivery-address" @click="toAddressPage">
      <div class="address-header">
        <h3>配送地址</h3>
        <i class="fa fa-angle-right"></i>
      </div>
      <div class="address-info" v-if="selectedAddress">
        <div class="address-icon">
          <i class="fa fa-map-marker"></i>
        </div>
        <div class="address-content">
          <div class="contact">
            <span class="name">{{ selectedAddress.contactName }}</span>
            <span class="phone">{{ selectedAddress.contactTel }}</span>
          </div>
          <div class="address">{{ selectedAddress.address }}</div>
        </div>
      </div>
      <div class="no-address" v-else>
        <i class="fa fa-plus-circle"></i>
        <span>请选择配送地址</span>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="payment-methods">
      <h3>支付方式</h3>
      <div class="method-list">
        <div 
          class="method-item" 
          :class="{ active: selectedPayment === 'alipay' }"
          @click="selectPayment('alipay')"
        >
          <div class="method-icon alipay-icon">
            <i class="fa fa-credit-card"></i>
          </div>
          <div class="method-name">支付宝</div>
          <div class="method-check" v-if="selectedPayment === 'alipay'">
            <i class="fa fa-check-circle"></i>
          </div>
        </div>
        
        <div 
          class="method-item" 
          :class="{ active: selectedPayment === 'wechat' }"
          @click="selectPayment('wechat')"
        >
          <div class="method-icon wechat-icon">
            <i class="fa fa-wechat"></i>
          </div>
          <div class="method-name">微信支付</div>
          <div class="method-check" v-if="selectedPayment === 'wechat'">
            <i class="fa fa-check-circle"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部支付按钮 -->
    <div class="bottom-bar">
      <div class="total-price">
        <span>合计:</span>
        <span class="price">¥{{ orderInfo?.orderTotal || orderInfo?.totalPrice }}</span>
      </div>
      <div class="pay-button" @click="handlePayment">
        立即支付
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getOrderById } from '@/api/orders';
import { getAddressById, getAddressList } from '@/api/address';
import { updateOrderStatus } from '@/api/payment';
import { ElMessage, ElLoading } from 'element-plus';
import { useUserInfoStore } from '../stores/user';

const route = useRoute();
const router = useRouter();
const orderId = route.query.orderId;
const userStore = useUserInfoStore();

const orderInfo = ref(null);
const selectedAddress = ref(null);
const selectedPayment = ref('alipay'); // 默认选择支付宝

// 获取用户地址列表中的第一个作为默认 - 添加更好的错误处理
const fetchDefaultAddress = async () => {
  try {
    // 用户ID应该从用户store获取，添加防御性判断
    const userId = userStore.userInfo?.id;
    if (!userId) {
      ElMessage.warning('请先登录');
      return false;
    }
    
    const res = await getAddressList(userId);
    if (res.code === 0 && res.data && res.data.length > 0) {
      // 确保地址对象包含必要的字段
      const address = res.data[0];
      if (!address.id && address.daId) {
        address.id = address.daId; // 兼容后端返回daId的情况
      }
      selectedAddress.value = address;
      return true;
    } else {
      ElMessage.warning('您还没有添加收货地址，请先添加地址');
      return false;
    }
  } catch (error) {
    console.error('获取默认地址失败:', error);
    ElMessage.error('获取地址信息失败');
    return false;
  }
};

// 获取订单信息 - 改进URL参数获取逻辑
const fetchOrderInfo = async () => {
  try {
    const res = await getOrderById(orderId);
    
    if (res.code === 0) {
      orderInfo.value = res.data;
      
      // 确保订单信息字段名称匹配
      if (orderInfo.value) {
        // 如果后端返回的是businessName字段
        if (!orderInfo.value.businessName && orderInfo.value.shopName) {
          orderInfo.value.businessName = orderInfo.value.shopName;
        }
        
        // 如果后端返回的是其他名称的订单金额字段
        if (!orderInfo.value.orderTotal && orderInfo.value.totalPrice) {
          orderInfo.value.orderTotal = orderInfo.value.totalPrice;
        }
      }
      
      // 获取地址信息
      if (orderInfo.value && orderInfo.value.daId) {
        const addressRes = await getAddressById(orderInfo.value.daId);
        if (addressRes.code === 0) {
          selectedAddress.value = addressRes.data;
        }
      }

      // 检查URL参数中是否有地址信息（从地址页面返回）- 改进逻辑
      if (route.query.addressId) {
        selectedAddress.value = {
          id: route.query.addressId,
          contactName: route.query.addressName || '未知用户',
          contactTel: route.query.addressPhone || '未知电话',
          address: route.query.addressDetail || '未知地址'
        };
      }
      // 如果还是没有地址，获取默认地址
      else if (!selectedAddress.value) {
        const addressFound = await fetchDefaultAddress();
        if (!addressFound) {
          ElMessage.warning('未找到收货地址，请添加地址');
        }
      }
    } else {
      ElMessage.error('获取订单信息失败: ' + res.message);
    }
  } catch (error) {
    ElMessage.error('获取订单信息出错');
  }
};

// 选择支付方式
const selectPayment = (method) => {
  selectedPayment.value = method;
};

// 跳转到地址页面
const toAddressPage = () => {
  router.push({
    path: '/address',
    query: { 
      orderId: orderId,
      returnTo: '/payment'
    }
  });
};

// 处理支付
const handlePayment = async () => {
  // 检查地址有效性
  if (!selectedAddress.value) {
    ElMessage.warning('请选择配送地址');
    return;
  }

  // 确保地址对象包含必要的字段
  const addressId = selectedAddress.value.id || selectedAddress.value.daId;
  if (!addressId) {
    ElMessage.warning('无效的地址信息，请重新选择地址');
    return;
  }
  
  try {
    // 显示加载状态
    const loading = ElLoading.service({
      lock: true,
      text: '支付处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    const res = await updateOrderStatus(
      orderInfo.value.orderId, 
      "PAID",
      selectedPayment.value === 'alipay' ? 1 : 2,
      addressId
    );
    loading.close();
    
    if (res.code === 0) { 
      ElMessage.success('支付成功');
      
      setTimeout(() => {
        router.push({
          path: '/payment/result',
          query: { 
            orderId: orderInfo.value.orderId,
            status: 'success',
            amount: orderInfo.value.orderTotal || orderInfo.value.totalPrice,
            businessId: orderInfo.value.businessId
          }
        });
      }, 1000);
    } else {
      ElMessage.error('支付失败: ' + (res.message || '请稍后重试'));
    }
  } catch (error) {
    console.error('支付失败:', error);
    ElMessage.error('支付失败，请重试');
  }
};

// 添加返回方法
const goBack = () => {
  if (orderInfo.value?.businessId) {
    router.push({
      path: '/businessInfo',
      query: { 
        businessId: orderInfo.value.businessId,
        from: 'index'  // 保持与首页传入的参数一致
      }
    });
  } else {
    router.go(-1);
  }
};

// 页面加载时获取订单信息
onMounted(() => {
  if (!orderId) {
    ElMessage.error('订单ID不能为空');
    router.push('/orders');
    return;
  }
  
  // 尝试解析订单ID，确保是有效值
  if (isNaN(parseInt(orderId))) {
    ElMessage.error('无效的订单ID');
    router.push('/orders');
    return;
  }
  
  fetchOrderInfo();
});
</script>

<style scoped lang="scss">
.wrapper {
  padding-bottom: 60px;
  background-color: #f7f7f7;
  min-height: 100vh;
}

header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  background-color: #ff6b01;
  color: white;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.order-info,
.delivery-address,
.payment-methods {
  margin: 15px;
  padding: 18px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
}

h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.price {
  color: #ff6b01;
  font-weight: bold;
}

// 优化配送地址样式
.delivery-address {
  padding: 0;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  
  .address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 18px;
    border-bottom: 1px solid #f5f5f5;
    
    h3 {
      margin: 0;
    }
    
    .fa-angle-right {
      color: #999;
      font-size: 16px;
    }
  }
  
  .address-info {
    display: flex;
    padding: 18px;
    
    .address-icon {
      width: 24px;
      height: 24px;
      margin-right: 10px;
      color: #ff6b01;
      font-size: 20px;
      align-self: flex-start;
      margin-top: 2px;
    }
    
    .address-content {
      flex: 1;
      
      .contact {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .name {
          font-size: 16px;
          font-weight: 500;
          margin-right: 10px;
        }
        
        .phone {
          font-size: 14px;
          color: #666;
        }
      }
      
      .address {
        font-size: 14px;
        color: #666;
        line-height: 1.5;
      }
    }
  }
  
  .no-address {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 25px 0;
    color: #999;
    font-size: 15px;
    
    i {
      margin-right: 8px;
      font-size: 18px;
      color: #ff6b01;
    }
  }
}

// 优化支付方式样式
.payment-methods {
  .method-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .method-item {
    display: flex;
    align-items: center;
    padding: 16px;
    border: 1px solid #eee;
    border-radius: 10px;
    position: relative;
    transition: all 0.2s ease;
    
    &:active {
      background-color: #fafafa;
    }
    
    &.active {
      border-color: #ff6b01;
      background-color: #fff8f3;
    }
  }

  .method-icon {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    font-size: 22px;
  }

  .alipay-icon {
    color: #00a0e9;
  }

  .wechat-icon {
    color: #09bb07;
  }

  .method-name {
    flex: 1;
    font-size: 16px;
    font-weight: 500;
  }

  .method-check {
    color: #ff6b01;
    font-size: 20px;
  }
}

// 优化底部支付按钮
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  background-color: white;
  padding: 12px 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.06);
}

.total-price {
  flex: 1;
  font-size: 16px;
}

.pay-button {
  background-color: #ff6b01;
  color: white;
  padding: 12px 24px;
  border-radius: 24px;
  font-weight: bold;
  font-size: 16px;
  box-shadow: 0 4px 10px rgba(255, 107, 1, 0.2);
  transition: all 0.2s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2px 6px rgba(255, 107, 1, 0.2);
  }
}
</style>